#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created on 2018/6/13
import math
import sys

from flask import render_template, request, jsonify, make_response
from app import util
from app.MySession import MySession
from dbConnection.MysqlConn import Mysql
from . import admin

reload(sys)
sys.setdefaultencoding('utf8')


# 后台登陆页面
@admin.route('/admin/login.html')
def login():
    return render_template('admin/login.html')


# 用户登陆
@admin.route('/admin_login_post', methods=['post'])
def admin_login_post():
    try:
        username = request.values.get('username')
        password = request.values.get('password')
        ip = request.headers.get('X-Real-Ip', request.remote_addr)
        sql = "select * FROM girl_admin WHERE username = '%s' AND password = '%s'" % (username, util.md5(str(password).strip()))
        mysql = Mysql()
        res = mysql.getOne(sql, None)
        mysql.dispose()
        if res:
            if res['permission'] == 2:
                return jsonify({'status':0})
            data = {
                'status': 1
            }
            re = make_response(jsonify(data))
            user = MySession.create_session(username)
            re.set_cookie('uid', user)
            add_login_log(username, ip, 1)
            update_user_login(username, ip)
            return re
        else:
            data = {
                'status':2
            }
            add_login_log(username, ip, 0)
            return jsonify(data)
    except Exception as e:
        print e
        data = {
            'status':3
        }
        return jsonify(data)


# 添加登陆记录表
def add_login_log(user, ip, depict):
    sql = "insert INTO girl_login_record(uname, login_ip, login_status, login_time) VALUES ('%s', '%s', '%s', now())"\
          % (user, ip, depict)
    mysql = Mysql()
    mysql.insertOne(sql, None)
    mysql.dispose()


# 更新用户登陆时间
def update_user_login(user, ip):
    sql = "update girl_admin SET login_time = now(), login_ip = '%s', login_count = login_count + 1 WHERE " \
          "username = '%s'" % (ip, user)
    mysql = Mysql()
    mysql.update(sql, None)
    mysql.dispose()